import fs from "fs";
import path from "path";
import { fileURLToPath } from "url";

const docsRoot = path.resolve(import.meta.dirname, "..", "docs");

console.log(docsRoot);

const tocjson = fs.readFileSync(
  path.join(docsRoot, ".vitepress/config/guide-toc.json"),
  "utf-8"
);

const toc = JSON.parse(tocjson);
const allitems = extractAllItems(toc);

const dest = path.join(docsRoot, "zh");

allitems.forEach(({ text, link }) => {
  if (link.endsWith("/")) link += "index";
  const file = path.join(dest, `${link}.md`);
  if (!fs.existsSync(file)) {
    const dir = path.dirname(file);
    if (!fs.existsSync(dir)) fs.mkdirSync(dir, { recursive: true });
    fs.writeFileSync(file, `# ${text}\nTODO`);
  }
});

function extractAllItems(items, results = []) {
  items.forEach((item) => {
    if (item.link) results.push({ text: item.text, link: item.link });
    if (item.items) extractAllItems(item.items, results);
  });

  return results;
}
